package com.sandy.demo.auth

import groovy.transform.CompileStatic
import groovy.transform.ToString
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails

/**
 *
 */
@ToString(includeNames = true, includeSuper = true, includes = ['principal', 'accessToken'])
@CompileStatic
class AccessToken extends AbstractAuthenticationToken {

    String accessToken

    /** The username */
    UserDetails principal

    AccessToken(Collection<? extends GrantedAuthority> authorities) {
        super(authorities)
        super.setAuthenticated(true)
    }

    AccessToken(UserDetails principal, Collection<? extends GrantedAuthority> authorities, String accessToken) {
        this(authorities)
        this.principal = principal
        this.accessToken = accessToken
    }

    AccessToken(String accessToken) {
        super(null)
        this.accessToken = accessToken
        super.setAuthenticated(false)
    }

    Object getCredentials() {
        return null
    }

    void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead")
        }

        super.setAuthenticated(false)
    }

}
